<?php
namespace Tongcheng\Controller;
use Think\Controller;
use Think\Think;

/**
 * Class BookController
 * @package Tongcheng\Controller
 *
 * 图书接口类
 */
class BookController extends CommonController {
    public function index(){
        $sd['is'] = '122';
        $sd['dd'] = '12122';
        $sd['uid'] = I('uid');
        $file =  I('file');
        $code = $_FILES['file'];
        if(is_array($code)){
            foreach ($code as $file){
                $fileName = $this->upload($file);
                if(!empty($fileName)){
                    $sd['filename'] = $fileName;
                    $sd['index'] = I('index');
                }
            }
        }else{
            $fileName = $this->upload($code);
            $sd['filename'] = $fileName;
            $sd['index'] = I('index');
        }
        $this->ajaxReturn(json_encode($sd),'JSON');
        exit();
//        $this->display();
    }

    /**
     * code兑换openid
     */
    public function codeToOpanId(){
        $appid = C("OPEN_APPID");
        $appsecret = C('OPEN_APPSECRET');
        $code = I('code');
        if(empty($code)){
            $this->ajaxReturn(0);
        }
        //通过接口获取用户openid
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appsecret.'&js_code='.$code.'&grant_type=authorization_code';
        $data = $this->ihttp_get($url,true);
        //临时用时间戳代替openid
        //创建用户
        $openid = json_decode($data)->openid;
        $session_key = json_decode($data)->session_key;
        $member = M('Member')->where('openid = "'.$openid.'"')->find();
        $member['ishave'] = 0;
        if(!empty($member['uid'])){
            $member = $this->getMember($member['uid']);
            if(!empty($member['nickname'])){
                $member['ishave'] = 1;
            }
            $this->ajaxReturn($member,'json');
        }
        $member['openid']=$openid;
        $member['wid']=2;
        $member['create_time']=time();
        $member['last_time']=time();
        $member['yajin']=0;
        $member['yu_e_num']=0;
        $member['session_key']=$session_key;
        $member['nickname']='';
        $member['headimgurl']='';
        $log_id = M('Member')->add($member);
        if(!$log_id){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn(array('uid'=>$log_id),'json');
        }
    }

    //更新用户昵称和头像
    public function buChongMember(){
        $uid = I('uid');
        $formdata = json_decode($_POST['userinfo']);
        $data['nickname'] = $formdata->nickName;
        $data['headimgurl'] = $formdata->avatarUrl;
        M('Member')->where('uid = '.$uid)->save($data);
        $member = $this->getMember($uid);
        if(!empty($member)){
            $this->ajaxReturn($member,'json');
        }else{
            $this->ajaxReturn(0);
        }

    }

    /**
     * @param $uid
     * @return
     * 获取封装后的用户信息
     */
    public function getMember($uid){
        $member = M('Member')->where('uid = '.$uid)->find();
        //余额区分整数和小数
        $yuE = $member['yu_e_num'];
        $yuEz = floor($yuE);
        $member['yuEz'] = $yuEz;
        $yuEx = round(($yuE - $yuEz) * 100);
        $member['yuEx'] = $yuEx<10?'0'.$yuEx:$yuEx;
        //获取发布闲置数量
        $unuse_num = 0;
        $unuse_num = M('Unuse')->where('uid = '.$uid)->select();
        $member['unuse_num'] = count($unuse_num);

        //获取发布图书数量
        $books_num = 0;
        $books_num = M('Books')->where('uid = '.$uid)->select();
        $member['books_num'] = count($books_num);
        //获取总收入
        //根据订单otheruid统计金额
        $num = M('')->query('select sum(ifnull(so.shouru,0)) num from tp_shop_order so where so.shuzhu_quren = 1 and  so.otheruid = '.$uid);
        $member['shouru_num'] = 0;
        if(!empty($num[0])){
            $member['shouru_num'] = $num[0]['num'];
        }
        return $member;
    }

    /**
     * 增加书籍
     */
    public function add(){
        $model = M("Books");
        $formdata = json_decode($_POST['formData']);
        $userInfo = $formdata->userInfo;
        $book['book_name'] =$formdata->book_name;
        $book['book_type'] =$formdata->unuse_type;
        $book['press'] =$formdata->press;
        $book['page_num'] =$formdata->page_num;
        $book['remark'] =$formdata->remark;
        $book['cover_img'] =$formdata->cover_img;
        $book['catalog_img1'] =$formdata->catalog_img1;
        $book['catalog_img2'] =$formdata->catalog_img2;
        $book['catalog_img3'] =$formdata->catalog_img3;
        $book['text_img1'] =$formdata->text_img1;

        $book['text_img2'] =$formdata->text_img2;
        $book['text_img3'] =$formdata->text_img3;
        $book['text_img4'] =$formdata->text_img4;
        $book['book_address'] =$formdata->book_address;
        $book['transaction_address1'] =$formdata->transaction_address1;
        $book['transaction_address2'] =$formdata->transaction_address2;
        $book['transaction_address3'] =$formdata->transaction_address3;
        $book['rent'] =$formdata->rent;
        $book['original_price'] =$formdata->original_price;
        $book['add_time'] =time();
        $book['author'] =$formdata->author;
        $book['uid'] = $userInfo->uid;
        $book['id'] = $formdata->id;
        $book['status'] = 1;
        $book['upstatus'] = 1;
        $book['city'] = $formdata->address->city;
        $book['province'] = $formdata->address->province;
        $book['lon'] = $formdata->address->otherlon;
        $book['lan'] = $formdata->address->otherlat;
        if(empty($formdata->id)){
            if($model->add($book)){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            if($model->save($book)){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }

    }

    /**
     * 获取发布的图书列表
     */
    public function getBookList(){
        $Model = M();
        $keyword = I('keyword');
        $city = I('city');
        $bow = I('bow');
        $latitude = I('latitude');
        $longitude = I('longitude');
        $sql = " ";
        $sql1 = " ";
        if(!empty($keyword)){
            $sql .= ' and b.book_name like "%'.$keyword.'%"';
            $sql1 .= ' and b.book_name like "%'.$keyword.'%"';
        }
        if(!empty($city) && 'undefined' != $city){
            $sql .= ' and b.book_address like "%'.mb_substr($city,0,2,"utf-8").'%"';
            $sql1 .= ' and b.book_address not like "%'.mb_substr($city,0,2,"utf-8").'%"';
        }

        //增加经纬度计算
        $juli = '0';
        $order = '';
        if(!empty($latitude) && 'undefined' != $latitude){
            $juli = ' LatLonRadiusDistance('.$longitude.',b.lon,'.$latitude.',b.lan) ';
            $order = ' order by LatLonRadiusDistance('.$longitude.',b.lon,'.$latitude.',b.lan) asc ';
        }

        //获取用户集合
        $list = $Model->query('select * from tp_member m  where 1=1 ');
        $newList = array();
        foreach($list as $member){
            //获取用户发布的图书
            $booksList1 = $Model->query('select b.*,'.$juli.' as juli from tp_books b where b.upstatus != 0 '.$sql.' and b.uid = '.$member['uid'].$order.' limit '.$bow);
            $member['booksList1'] = $booksList1;
            $booksList2 = $Model->query('select b.* ,'.$juli.' as juli from tp_books b where b.upstatus != 0 '.$sql.' and b.uid = '.$member['uid'].$order.' limit '.$bow.','.$bow);
            $member['booksList2'] = $booksList2;
            if(empty($booksList1) && empty($booksList2)){
                continue;
            }
            array_push($newList,$member);
        }

        //获取非城市集合
        foreach ($list as $member){
            //获取用户发布的图书
            $booksList1 = $Model->query('select b.*,'.$juli.' as juli from tp_books b where b.upstatus != 0 '.$sql1.' and b.uid = '.$member['uid'].$order.' limit '.$bow);
            $member['booksList1'] = $booksList1;
            $booksList2 = $Model->query('select b.* ,'.$juli.' as juli from tp_books b where b.upstatus != 0 '.$sql1.' and b.uid = '.$member['uid'].$order.' limit '.$bow.','.$bow);
            $member['booksList2'] = $booksList2;
            if(empty($booksList1) && empty($booksList2)){
                continue;
            }
            array_push($newList,$member);
        }
        //搜索不带广告位
        if(empty($keyword)){
            //增加广告位
            $guanggaolist = M('Guanggao')->order('weizhi asc')->select();
            if(!empty($guanggaolist)){
                foreach ($guanggaolist as &$item){
                    $index = intval($item['weizhi']);
                    $newList = $this->insertArray($newList,$index,$item);
                }
            }
        }

        if(empty($list)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($newList,'json');
        }
    }

    /**
     * 获取客服海报
     */
    public function getHaiBao(){
        $id = I('id');
        $wechat = M('Wechat')->where('wid = 2')->find();
        if(!empty($id) && undefined != $id){
            $result = M('KefuWenda')->where('id = '.$id)->find();
            if(!empty($result)){
                $wechat['info'] = $result;
            }
        }

        if(!empty($wechat)){
            $this->ajaxReturn($wechat,'json');
        }else{
            $this->ajaxReturn(0);
        }

    }

    /**
     * 保存意见反馈
     */
    public function saveFanKui(){
        $_GET['add_time']=time();
        $result = M('KefuWenda')->add($_GET);
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }


    /**
     * 获取反馈信息
     */
    public function getFanKui(){
        $uid = I('uid');
        $fanKuiList = M('KefuWenda')->where('uid = '.$uid)->select();
        if(empty($fanKuiList)){
            $this->ajaxReturn(0);
        }
        $this->ajaxReturn($fanKuiList,'json');
    }

    /**
     * @param $list
     * @param $index
     * @param $item
     * 添加到数组
     */
    public function insertArray($list,$index,$item){
        $list1 = array_slice($list,0,$index-1);
        $list2 = array_slice($list,$index-1);
        $item['isguanggao']=1;
        array_push($list1,$item);
        return array_merge($list1,$list2);
    }


    //根据type 获取数据字典数据
    public function getDocDicByType($type){
        $model = M();
        $value = I('type');
        $value = empty($value)?$type:$value;
        $where = " ";
        if(!empty($value)){
            $where = " and a.value = '".$value."'";
        }else{
            $this->ajaxReturn(0);
        }
        $list = $model->query('select a.id aid,a.value avalue,a.type atype,b.id bid,b.value bvalue,b.type btype,0 as isselect from tp_docdic a inner join tp_docdic b on b.pid = a.id where a.pid = 0 and b.cid = 0 '.$where.' order by b.id asc ');
        if(empty($list)){
            $this->ajaxReturn(0);
        }
        foreach ($list as &$item){
            if(!empty($item)){
                //获取二级分类
                $erjilist = $model->query('select * from tp_docdic c where c.pid = '.$item['aid'].' and c.cid = '.$item['bid']);
                if(!empty($erjilist)){
                    $item['erji'] = $erjilist;
                }else{
                    $item['erji'] = array();
                }
            }
        }
        $this->ajaxReturn($list,'json');
    }

    //获取用户的所有相关书籍信息
    public function getBookInfoByUid(){
        $model = M();
        $latitude = I('latitude');
        $longitude = I('longitude');
        //用户uid
        $uid = I('uid');
        $myid = I('myid');

        //增加经纬度计算
        $juli = '0';
        if(!empty($latitude) && 'undefined' != $latitude){
            $juli = ' LatLonRadiusDistance('.$longitude.',b.lon,'.$latitude.',b.lan) ';
        }

        //获取图书及用户信息
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        $newResult = '';
        $member = $model->query('select * from tp_member m where m.uid = '.$uid);

        if(empty($member)){
            $this->ajaxReturn(0);
        }
        //获取相关书籍信息
        $newResult = $member[0];
        $booksList = $model->query('select b.*, '.$juli.' as juli from tp_books b where b.upstatus != 0 and b.uid = '.$uid);
        if(empty($booksList)){
            $this->ajaxReturn(0);
        }else{
            $newResult['booksList'] = $booksList;
            foreach ($booksList as &$item){
                $order = M('')->query('select * from tp_shop_order ts where ts.status = 2 and ts.type = 1 and ts.otherid = '.$item['id'].' and ts.uid = '.$myid);
                if(!empty($order)){
                    $item['isjieyue'] = 1;
                }else{
                    $item['isjieyue'] = 0;
                }
            }
            unset($item);
            $this->ajaxReturn($newResult,'json');
        }
    }

    /**
     * 获取书本详情
     */
    public function getBookInfo(){
        $model = M('');
        $id = I('id');
        $uid = I('uid');
        $latitude = I('latitude');
        $longitude = I('longitude');
        $type = I('type');//无或0为正常1续借2卖家查看
        //增加经纬度计算
        $juli = '0';
        if(!empty($latitude) && 'undefined' != $latitude){
            $juli = ' LatLonRadiusDistance('.$longitude.',b.lon,'.$latitude.',b.lan) ';
        }

        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $bookinfo = $model->query('select b.*,'.$juli.' as juli,m.* from tp_books b left join tp_member m on m.uid = b.uid where b.id = '.$id);
        if(empty($bookinfo[0])){
            $this->ajaxReturn(0);
        }
        //增加书本相关图片数组
        $imglist = array();
        if(!empty($bookinfo[0]['catalog_img1'])){
            array_push($imglist,$bookinfo[0]['catalog_img1']);
        }
        if(!empty($bookinfo[0]['catalog_img2'])){
            array_push($imglist,$bookinfo[0]['catalog_img2']);
        }
        if(!empty($bookinfo[0]['catalog_img3'])){
            array_push($imglist,$bookinfo[0]['catalog_img3']);
        }
        if(!empty($bookinfo[0]['text_img1'])){
            array_push($imglist,$bookinfo[0]['text_img1']);
        }
        if(!empty($bookinfo[0]['text_img2'])){
            array_push($imglist,$bookinfo[0]['text_img2']);
        }
        if(!empty($bookinfo[0]['text_img3'])){
            array_push($imglist,$bookinfo[0]['text_img3']);
        }
        if(!empty($bookinfo[0]['text_img4'])){
            array_push($imglist,$bookinfo[0]['text_img4']);
        }
        $bookinfo[0]['imglist'] = $imglist;


        /*** 计算需要支付的押金***/
        if(!empty($uid)){
            $member = M('Member')->where('uid = '.$uid)->find();
            if(empty($member)){
                $this->ajaxReturn(0);
            }
        }
        //活动押金和冻结押金
        //活动押金
        $yajin = $member['yajin'];
        $xuyajin = 0;
        $oid = I('oid');
        if(!empty($type) && 'undefined' != $type && 1 == intval($type)){
            //若为续借，需要交付的押金为0，若存在逾期扣除押金情况，则续交押金为扣除的押金总和

            if(!empty($oid) && 'undefined' != $oid){
                $yajinloglist = M('')->query('select ifnull(sum(t.amount),0) num from tp_yajin_log t where t.type = 3 and t.status = 0 and t.oid = '.$oid);
                if(!empty($yajinloglist[0])){
                    $xuyajin = $yajinloglist[0]['num'];
                }
            }

        }else if(!empty($type) && 'undefined' != $type && 2 == intval($type)){//卖家查看
            //根据订单获取到买家信息
            $orderid = $bookinfo[0]['order_id'];
            $oid = $orderid;
            if(empty($orderid)){
                $this->ajaxReturn(0);
            }
            $shoporders = M('')->query('select * from tp_shop_order ts left join tp_member m on ts.uid = m.uid where ts.id = '.$orderid);
            if(!empty($shoporders[0])){
                $shoporders[0]['dao_qi_time'] = intval($shoporders[0]['dao_qi_time']) - time();
                $bookinfo[0]['maiuseinfo'] = $shoporders[0];
            }

        }else{
            if(floatval($yajin)>=floatval($bookinfo[0]['original_price'])){
                $xuyajin = 0;
            }else{
                $xuyajin = floatval($bookinfo[0]['original_price'])-floatval($yajin);
            }
        }

        $bookinfo[0]['xuyajin'] = $xuyajin;
        $tian = 0;
        $dao_qi_time = 0;
        $ostatus = 0;
        if(!empty($oid) && 'undefined' != $oid){
            $shoporder = M('ShopOrder')->where('id = '.$oid)->find();
            if(!empty($shoporder)){
                $tian = $shoporder['tian'];
                $dao_qi_time = $shoporder['dao_qi_time'];
                $ostatus = $shoporder['status'];
            }
        }
        $bookinfo[0]['tian'] = $tian;
        if(intval($dao_qi_time) <= time()){
            $bookinfo[0]['dao_qi_time'] = time() - intval($dao_qi_time);
            $bookinfo[0]['isyuqi'] = 1;
        }else{
            $bookinfo[0]['dao_qi_time'] = intval($dao_qi_time) - time();
            $bookinfo[0]['isyuqi'] = 0;
        }
        $bookinfo[0]['ostatus'] = $ostatus;
        $bookinfo[0]['formtype'] = $type;
        $this->ajaxReturn($bookinfo[0],'json');

    }

    /**
     * 获取发布的闲置列表
     */
    public function getUnuseList(){
        $model = M();
        $keyword = I('keyword');
        $currentTab = I('currentTab');
        $latitude = I('latitude');
        $longitude = I('longitude');
        $pageSize = 1 == $currentTab?10:5;
        $pageNum = I('pageNum');
        $uid = I('uid');
        if(empty($pageNum)){
            $pageNum = 1;
        }
        $sql = " ";
        if(!empty($keyword) && intval($currentTab) == 1){
            $sql.=' and u.unuse_name like "%'.$keyword.'%"';
        }
        //增加经纬度计算
        $juli = '0';
        if(!empty($latitude) && 'undefined' != $latitude){
            $juli = ' LatLonRadiusDistance('.$longitude.',u.longitude,'.$latitude.',u.latitude) ';
        }

        //为推荐
        if(!empty($currentTab)){
            $sql.='  ';//and u.is_tuijian = 1
            $sql.= ' order by u.add_time desc '.' limit '.($pageNum-1)*$pageSize.','.$pageSize;
        }else{
            if('0' != $juli){
                $sql.= ' order by '.$juli.' asc '.' limit '.($pageNum-1)*$pageSize.','.$pageSize;
            }else{
                $sql.= ' order by u.id desc '.' limit '.($pageNum-1)*$pageSize.','.$pageSize;
            }
        }
        $list = $model->query('select *,0 as isdianzan ,'.$juli.' as juli from tp_unuse u left join tp_member m on m.uid = u.uid where 1=1 and u.status=1 '.$sql);
        //判断是否点赞
        foreach($list as &$item){
            $dianzanlog = $model->query('select * from tp_dianzan_log dl where dl.uid = '.$uid.' and dl.otherid = '.$item['id'].' and dl.from = '.(intval($item['type'])+2));
            if(!empty($dianzanlog)){
                $item['isdianzan'] = 1;
            }
        }
        unset($item);
        //获取收藏数目
        foreach($list as &$item){
            $shoucanglist = $model->query('select * from tp_shoucang_log sl where sl.otherid = '.$item['id']);
            if(!empty($shoucanglist)){
                $item['shoucangnum'] = count($shoucanglist);
            }else{
                $item['shoucangnum'] = 0;
            }
        }
        unset($item);
        //获取评论数目
        foreach ($list as &$item){
            $pinglunlist = $model->query('select * from tp_pinglun tp where tp.from = 1 and tp.otherid = '.$item['id']);
            if(!empty($pinglunlist)){
                $item['pinglunnum'] = count($pinglunlist);
            }else{
                $item['pinglunnum'] = 0;
            }
        }
        unset($item);

        if(empty($list)){
            $this->ajaxReturn(0);
        }else{
            if(1 == $currentTab){
                $newresult = '';
                $newList1 = array();
                $newList2 = array();
                foreach ($list as $key=>$item){
                    if($key%2==0){
                        array_push($newList1,$item);
                    }else{
                        array_push($newList2,$item);
                    }
                }
                $newresult['newList1'] = $newList1;
                $newresult['newList2'] = $newList2;
                $this->ajaxReturn($newresult,'json');
            }
            $this->ajaxReturn($list,'json');
        }
    }

    /**
     * 全局点赞接口
     */
    public function dianZan(){
        $model = M('DianzanLog');
        $formData = json_decode($_POST['formData']);
        //获取点赞的用户uid
        //获取要点赞的模块from   1闲置 2图书 3社区的书评 4社区的话题 5社区的问答 6社区的写文 7某个回复
        //获取具体要点赞的数据otherid
        $data['uid'] = I('uid');
        $data['otherid'] = $formData->otherid;
        $data['from'] = $formData->from;
        $dianZanLog = $model->where($data)->find();
        if(!empty($dianZanLog)){
            $model->where($data)->delete();
            $this->ajaxReturn(2);//取消点赞
        }
        $data['add_time'] = time();

        if(!$log_id = $model->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn(1);
        }
    }


    /**
     * 全局评论接口
     */
    public function pingLun(){
        //1闲置 2图书 3社区的书评 4社区的话题 5社区的问答 6社区的写文 7某个回复
        $formData = json_decode($_POST['formData']);
        //评论者uid
        $uid = I('uid');
        //评论内容content
        $content = $formData->pingLunContent;
        //评论模块from
        $from = $formData->from;
        //评论数据otherid
        $otherid = $formData->otherid;
        $data['wid'] = 2;
        $data['uid'] = $uid;
        $data['from'] = $from;
        $data['add_time'] = time();
        $data['otherid'] = $otherid;
        $data['content'] = $content;
        $model = M('Pinglun');
//        $pinglun = $model->query('select * from tp_pinglun pl where pl.uid = '.$uid.' and pl.otherid = '.$otherid.' and pl.from = '.$from);
//        if(!empty($pinglun)){
//            $this->ajaxReturn(array('code'=>2),'json');
//        }
        if(!$log_id = $model->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(array('code'=>0),'json');
        }else{
            $this->ajaxReturn(array('code'=>1),'json');
        }
    }

    /**
     * 全局收藏
     */
    public function shouCang(){
        $model = M('ShoucangLog');
        $formData = json_decode($_POST['formData']);
        $data['uid'] = I('uid');
        //from模块区分  1图书2闲置
        $data['from'] = $formData->from;
        $data['otherid'] = $formData->otherid;
        //判断是否已经收藏
        $shoucangdata =  $model->where($data)->select();
        if(!empty($shoucangdata)){
            $this->ajaxReturn(2,'json');
        }
        $data['remark'] = '收藏';
        $data['add_time'] = time();

        if(!$log_id = $model->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn(1);
        }
    }


    //获取收藏列表
    public function getShouCangList(){
        $model = M('');
        $pagesize = 5;
        $pagenum = I('pagenum');
        $uid = I('uid');
        //1图书2闲置
        $type = I('type');
        $type = $type==0?2:1;
        $join = '';
        if(1 == $type){
            $join.=' left join tp_books b on b.id = tsl.otherid ';
        }else if(2 == $type){
            $join.=' left join tp_unuse tu on tu.id = tsl.otherid ';
        }
        $order = ' order by tsl.id desc limit '.(($pagenum-1)*$pagesize).','.$pagesize;
        $shoucanglist = $model->query('select *,tsl.id tid from tp_shoucang_log tsl '.$join.' where tsl.from = '.$type.' and tsl.uid = '.$uid.$order);
        if(empty($shoucanglist)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($shoucanglist,'json');
        }
    }

    /**
     * 添加闲置
     */
    public function addXianZhi(){
        $model = M("Unuse");
        $formdata = json_decode($_POST['formData']);
        $userInfo = $formdata->userInfo;
        $book['unuse_name'] =$formdata->unuse_name;
        $book['unuse_info'] =$formdata->unuse_info;
        $book['unuse_address'] =$formdata->unuse_address;
        $book['is_new'] =$formdata->isQuanXin;
        $book['longitude'] =$formdata->address->otherlon;
        $book['latitude'] =$formdata->address->otherlat;
        $book['city'] =$formdata->address->city;
        $book['province'] =$formdata->address->province;
        $book['township'] =$formdata->address->township;
        $book['district'] =$formdata->address->district;

        $imgs = $formdata->uploadimages;
        foreach ($imgs as $key=>$img){
            $book['img'.($key+1)]=$img->filename;
        }
        $book['unuse_type'] =$formdata->unuse_type;
        $book['price'] =empty($formdata->price)?0:$formdata->price;
        $book['original_price'] =empty($formdata->original_price)?0:$formdata->original_price;
        $book['is_free_post'] =$formdata->is_free_post;
        $book['freight'] =empty($formdata->freight)?0:$formdata->freight;
        $book['add_time'] =time();
        $book['uid'] =$userInfo->uid;
        $book['id'] = $formdata->id;
        $book['status'] = 1;
        if(empty($formdata->id)){
            if($model->add($book)){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            if($model->save($book)){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }

    }


    /**
     * 获取闲置详情
     */
    public function getUnuseInfo(){
        $model = M('');
        $id = I('id');
        $latitude = I('latitude');
        $longitude = I('longitude');
        $sql = ' ';
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $sql .= ' and t.id = '.$id;
        //增加经纬度计算
        $juli = '0';
        if(!empty($latitude) && 'undefined' != $latitude){
            $juli = ' ifnull(LatLonRadiusDistance('.$longitude.',t.longitude,'.$latitude.',t.latitude),0.01) ';
        }
        $unuseinfo = $model->query('select *,'.$juli.' as juli from tp_unuse t left join tp_member m on m.uid = t.uid where 1=1 '.$sql);
        $newResult = '';
        $imageArray = array();
        if(empty($unuseinfo)){
            $this->ajaxReturn(0);
        }else{
            $newResult = $unuseinfo[0];
            for($i=0;$i<12;$i++){
                $imge = $unuseinfo[0]['img'.($i+1)];
                if(!empty($imge)){
                    array_push($imageArray,$imge);
                }
            }
            //判断是否收藏
            $uid = I('uid');
            if(!empty($uid) && 'undefined' != $uid){
                $shoucangdata = $model->query('select * from tp_shoucang_log tl where tl.from = 2 and tl.uid = '.$uid.' and tl.otherid = '.$unuseinfo[0]['id']);
                if(empty($shoucangdata)){
                    $newResult['isshoucang'] = 0;
                }else{
                    $newResult['isshoucang'] = 1;
                }
            }
            $newResult['imagearray'] = $imageArray;
            //获取评论数组
            $pinglunlist = $model->query('select *,FROM_UNIXTIME(pl.add_time,"%m-%d %H:%i") time from tp_pinglun pl left join tp_member m on m.uid = pl.uid where pl.from = 1 and pl.otherid = '.$id);
            $newResult['pinglunlist'] = $pinglunlist;
            $this->ajaxReturn($newResult,'json');
        }
    }

    /**
     * 获取闲置分类
     */
    public function getUnuseType(){
        $type = 'xianzhitype';
        $unUseType = $this->getDocDicByType($type);
        if(empty($unUseType)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($unUseType,'json');
        }
    }

    /**
     * @throws
     * 购买闲置接口
     */
    public function gouMaiUnuse(){
        $isyue = I('isyue');
        $isweixin = I('isweixin');
        $oid = I('oid');
        $map['wid'] = 2;
        $wechat = M("Wechat")->where($map)->find();

//        $top = M("Join")->where(array('id'=>$_POST['join_id']))->find();
//        $join_fee = $top['price'];
//        $join_days = $top['days'];

//        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = 2;//session('wid');
//        $data['shop_id'] = I('shop_id');
        $data['openid'] = I('openid');
        $data['otherid'] = I('otherid');
        $data['out_trade_no'] = 'XZ'.$this->build_order_no();
        $data['title'] = "购买闲置";
        $data['remark'] = $_POST['name'];
        $data['price'] = I('price');
        $data['pay_money'] = I('zongprice');
        $data['yun_fei'] = I('freight');
        $data['phone'] = I('phone');
        $data['address'] = I('address');
        $data['liuyan'] = I('liuyan');
        $data['shuzhu_quren'] = 0;

        $data['uid'] = I('uid');
//        $data['join_days'] = $join_days;
        $data['status'] = 1;//1待付款2待发货3待收货4已完成
        $data['is_pay'] = 0;
        $data['type'] = 2;
        $data['create_time'] = date("Y-m-d H:i:s");
        //根据otherid获取商品信息获取otheruid
        $goodinfo = M('')->query('select * from tp_unuse u where u.id = '.$data['otherid']);
        if(!empty($goodinfo[0])){
            $data['otheruid'] = $goodinfo[0]['uid'];
        }
        //判断是否在订单支付
        if(empty($oid)){
            if(!$log_id = M("ShopOrder")->add($data)){
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn(0);
            }
        }else{
            $datas = M('ShopOrder')->where('id = '.$oid)->select();
            if(empty($datas[0])){
                $this->ajaxReturn(0);
            }else{
                $data = $datas[0];
                $log_id = $oid;
            }
        }
        //更新order_id
        M('Unuse')->where('id = '.$goodinfo[0]['id'])->save(array('order_id'=>$log_id));

        //增加系统通知
        $this->addXiTongLog($log_id,1,I('uid'),$data['otheruid'],I('otherid'),'');

        //余额支付
        if(1 == $isyue){
            //扣除余额，并修改订单状态
            $member = M('Member')->where('uid = '.$data['uid'])->select();
            if(empty($member[0])){
                $this->ajaxReturn(0);
            }else{
                $yue = floatval($member[0]['yu_e_num']) - floatval($data['price']);
                $update['yu_e_num'] = $yue;
                M('Member')->where('uid = '.$member[0]['uid'])->save($update);
                //修改订单状态为待发货
                M('ShopOrder')->where("id = ".$log_id)->save(array('status'=>2,'is_pay'=>1));
                $this->ajaxReturn(1);
            }
        }

        if(1 == $isweixin){
            if(I('price') <= 0){
                $eq['id'] = $log_id;
                M("ShopOrder")->where($eq)->setField('is_pay',1);
                return false;
            }
//        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/renewShop",array('type'=>'unuse'));
            $url = "https://".$_SERVER['HTTP_HOST']."/index.php/Tongcheng/Notify2?type=1";
//            echo $url;
//            $this->ajaxReturn($url);
//            exit();
            vendor('Weixinpay.WxPayJsApiPay');
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($data['title']);
            $input->SetAttach($data['title']);
            $input->SetOut_trade_no($data['out_trade_no']);
            $input->SetTotal_fee(($data['pay_money']*100));
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            // $input->SetGoods_tag("test3");
            $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($data['openid']);
            $input->SetAppid($appid);
            $input->SetMch_id($mch_id);
            try{
                $wxorder = \WxPayApi::unifiedOrder($input, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
            if($wxorder['return_code'] == "FAIL"){
                $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
                $this->ajaxReturn($arr);
            }
            try{
                $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
            echo $jsApiParameters;
            exit();
        }
    }

    /**
     * @param $orderid
     * @param $type
     * @param $uid
     * 增加系统通知
     */
    public function addXiTongLog($orderid,$type,$uid,$maiuid,$otherid,$remark){

        $data['uid']=$uid;
        $data['maiuid']=$maiuid;
        $data['goods_id']=$otherid;
        $data['type']=$type;//1闲置2图书3借书归还4借书逾期5收入6闲置确认收获7续借
        $data['status']=0;
        $data['add_time']=time();
        $data['order_id']=$orderid;
        $data['remark']=$remark;
        M('XitongLog')->add($data);//增加系统通知
    }

    /**
     * 确认购买图书接口
     */
    public function gouMai(){

        //首先判断是否已借阅
        $shopOrder = M('ShopOrder')->where('type = 1 and status = 2 and otherid = '.I('otherid'))->select();
        if(!empty($shopOrder)){
            $this->ajaxReturn(2);
        }
        $isyue = I('isyue');
        $isweixin = I('isweixin');
        $map['wid'] = 2;
        $wechat = M("Wechat")->where($map)->find();

//        $top = M("Join")->where(array('id'=>$_POST['join_id']))->find();
//        $join_fee = $top['price'];
//        $join_days = $top['days'];

//        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = 2;//session('wid');
        $data['shop_id'] = I('shop_id');
        $data['uid'] = I('uid');
        $data['otherid'] = I('otherid');
        $data['openid'] = I('openid');
        $data['out_trade_no'] = 'BK'.$this->build_order_no();
        $data['title'] = "购买书籍";
        $data['remark'] = $_POST['name'];
        $data['price'] = I('price');
        $data['pay_money'] = I('price');
        $data['yuanjia'] = I('yuanjia');
        $data['tian'] = I('tian');
        $data['xuyajin'] = I('xuyajin');
        $data['shuzhu_quren'] = 0;
//        $data['join_days'] = $join_days;
        $data['status'] = 1;//1待收货2借阅中3已逾期4已归还
        $data['is_pay'] = 0;
        $data['type'] = 1;
        $data['create_time'] = date("Y-m-d H:i:s");
        //根据otherid获取商品信息获取otheruid
        $goodinfo = M('')->query('select * from tp_books u where u.id = '.$data['otherid']);
        if(!empty($goodinfo[0])){
            $data['otheruid'] = $goodinfo[0]['uid'];
        }
        if(!$log_id = M("ShopOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }

        /**
         * 增加系统通知
         */
        $data['uid']=I('uid');
        $data['maiuid']=$data['otheruid'];
        $data['goods_id']=I('otherid');
        $data['type']=2;//1闲置2图书
        $data['status']=0;
        $data['add_time']=time();
        $data['order_id']=$log_id;
        M('XitongLog')->add($data);//增加系统通知
        //修改图书的order_id
        M('Books')->where('id = '.$goodinfo[0]['id'])->save(array('order_id'=>$log_id));

        //增加押金记录
        if(!empty($data['xuyajin'])){
            $this->yaJinLog($log_id,1,$data['xuyajin'],$data['uid']);
        }

        //余额支付
        if(1 == $isyue){
            //扣除余额，并修改订单状态
            $member = M('Member')->where('uid = '.$data['uid'])->select();
            if(empty($member[0])){
                $this->ajaxReturn(0);
            }else{
                $yue = floatval($member[0]['yu_e_num']) - floatval($data['price']);
                $update['yu_e_num'] = $yue;

                M("ShopOrder")->where('id = '.$log_id)->save(array('is_pay'=>1));
                $shoporder = M("ShopOrder")->where('id = '.$log_id)->select();
                //修改用户的活动押金和冻结押金
                //活动押金
                $yajin = $member[0]['yajin'];
                //冻结押金
                $dong_jie_yajin = $member[0]['dong_jie_yajin'];
                //1.如果活动押金大于书本的押金则 冻结押金=原冻结+书本押金，活动押金=原活动-书本押金，交付押金0
                if(floatval($yajin)>=floatval($shoporder[0]['yuanjia'])){
                    $dong_jie_yajin = floatval($dong_jie_yajin)+floatval($shoporder[0]['yuanjia']);
                    $yajin = floatval($yajin)-floatval($shoporder[0]['yuanjia']);

                }else{
                    //2,如果活动押金小于书本押金  冻结押金=原冻结+书本押金 ，活动押金=0，交付押金=书本押金-活动押金
                    $dong_jie_yajin = floatval($dong_jie_yajin)+floatval($shoporder[0]['yuanjia']);
                    $yajin = 0;
                }
                $update['yajin'] = $yajin;
                $update['dong_jie_yajin'] = $dong_jie_yajin;
                //修改书本状态为已付款
                M('Books')->where('id = '.$data['otherid'])->save(array('status'=>2));

                M('Member')->where('uid = '.$member[0]['uid'])->save($update);
                $this->ajaxReturn(array('oid'=>$log_id,'id'=>$data['otherid'],'ostatus'=>1),'json');
            }
        }
        //微信支付
        if(1 == $isweixin){

            if(I('price') <= 0){
                $eq['id'] = $log_id;
                M("ShopOrder")->where($eq)->setField('is_pay',1);
                return false;
            }
            $url = "https://".$_SERVER['HTTP_HOST']."/index.php/Tongcheng/Notify2?type=2";
//            echo $url;
//            $this->ajaxReturn($url);
            // echo $url;
            vendor('Weixinpay.WxPayJsApiPay');
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($data['title']);
            $input->SetAttach($data['title']);
            $input->SetOut_trade_no($data['out_trade_no']);
            $input->SetTotal_fee(($data['pay_money']*100));
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            // $input->SetGoods_tag("test3");
            $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($data['openid']);
            $input->SetAppid($appid);
            $input->SetMch_id($mch_id);
            try{
                $wxorder = \WxPayApi::unifiedOrder($input, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
            if($wxorder['return_code'] == "FAIL"){
                $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
                $this->ajaxReturn($arr);
            }
            try{
                $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
            echo $jsApiParameters;
            exit();
        }

    }


    /**
     * 确认续借图书接口
     */
    public function xueJieGouMai(){
        $pid = I('pid');
        $uid = I('uid');
        if(empty($pid)){
            $this->ajaxReturn(0);
        }
        $porder = M('ShopOrder')->where('id = '.$pid)->find();
        if(empty($porder)){
            $this->ajaxReturn(0);
        }
        //首先判断是否已借阅（若为统一用户可以续借）
        $shopOrder = M('ShopOrder')->where('type = 1 and status = 2 and otherid = '.I('otherid'))->select();
        if(!empty($shopOrder[0]) && intval($uid) != intval($shopOrder[0]['uid'])){
            $this->ajaxReturn(2);
        }
        $isyue = I('isyue');
        $isweixin = I('isweixin');
        $map['wid'] = 2;
        $wechat = M("Wechat")->where($map)->find();

//        $top = M("Join")->where(array('id'=>$_POST['join_id']))->find();
//        $join_fee = $top['price'];
//        $join_days = $top['days'];

//        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = 2;//session('wid');
        $data['shop_id'] = I('shop_id');
        $data['uid'] = I('uid');
        $data['otherid'] = I('otherid');
        $data['openid'] = I('openid');
        $data['out_trade_no'] = 'BK'.$this->build_order_no();
        $data['title'] = "购买书籍";
        $data['remark'] = $_POST['name'];
        $data['price'] = I('price');
        $data['pay_money'] = I('price');
        $data['yuanjia'] = I('yuanjia');
        $data['tian'] = I('tian');
        $data['xuyajin'] = I('xuyajin');
        $data['shuzhu_quren'] = 0;
//        $data['join_days'] = $join_days;
        $data['status'] = 1;//1待收货2借阅中3已逾期4已归还
        $data['is_pay'] = 0;
        $data['type'] = 4;// 4续借
        $data['pid'] = $pid;
        $data['create_time'] = date("Y-m-d H:i:s");
        //根据otherid获取商品信息获取otheruid
        $goodinfo = M('')->query('select * from tp_books u where u.id = '.$data['otherid']);
        if(!empty($goodinfo[0])){
            $data['otheruid'] = $goodinfo[0]['uid'];
        }
        if(!$log_id = M("ShopOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }

        /**
         * 增加系统通知
         */
        $this->addXiTongLog($log_id,7,I('uid'),$data['otheruid'],I('otherid'),'续借');

        //余额支付
        if(1 == $isyue){
            //扣除余额，并修改订单状态
            $member = M('Member')->where('uid = '.$data['uid'])->select();
            if(empty($member[0])){
                $this->ajaxReturn(0);
            }
            $yue = floatval($member[0]['yu_e_num']) - floatval($data['price']);
            $update['yu_e_num'] = $yue;

            M("ShopOrder")->where('id = '.$log_id)->save(array('is_pay'=>1));
            $shoporder = M("ShopOrder")->where('id = '.$log_id)->select();
            //修改用户的活动押金和冻结押金
            //活动押金
            $yajin = $member[0]['yajin'];
            //冻结押金
            $dong_jie_yajin = $member[0]['dong_jie_yajin'];
            //1.如果活动押金大于书本的押金则 冻结押金=原冻结+书本押金，活动押金=原活动-书本押金，交付押金0
            if(floatval($yajin)>=floatval($shoporder[0]['xuyajin'])){
                $dong_jie_yajin = floatval($dong_jie_yajin)+floatval($shoporder[0]['xuyajin']);
                $yajin = floatval($yajin)-floatval($shoporder[0]['xuyajin']);

            }else{
                //2,如果活动押金小于书本押金  冻结押金=原冻结+书本押金 ，活动押金=0，交付押金=书本押金-活动押金
                $dong_jie_yajin = floatval($dong_jie_yajin)+floatval($shoporder[0]['xuyajin']);
                $yajin = 0;
            }
            $update['yajin'] = $yajin;
            $update['dong_jie_yajin'] = $dong_jie_yajin;

            M('Member')->where('uid = '.$member[0]['uid'])->save($update);
            //修改父订单状态为借阅中,增加到期时间几天后及天数和租金
            $fuorder = M('ShopOrder')->where('id = '.$pid)->find();
            $tian = intval($fuorder['tian']) + intval(I('tian'));
            $pay_money = floatval($fuorder['pay_money']) + floatval(I('price'));
            $xuyajin = floatval($fuorder['xuyajin']) + floatval(I('xuyajin'));
            if(!empty($fuorder)){
                $daoqitime = strtotime('+'.intval(I('tian')).' days',$fuorder['dao_qi_time']);
                //若为逾期续借，则到期时间为当前时间加上逾期天数+天数
                if(3 == $fuorder['status']){
                    //首先获取逾期时间
                    $yuqitime = time()-$fuorder['dao_qi_time'];
                    $yuqitian = 0;
                    if($yuqitime/86400>=1){
                        //大于一天
                        $yuqitian = floor($yuqitime/86400);
                        $yuqitime = $yuqitime-floor($yuqitime/86400)*86400;
                        $daoqitime = time() + (86400*intval(I('tian')) - $yuqitime);
                    }else{
                        //在一天内
                        $daoqitime = time() + (86400*intval(I('tian')) - $yuqitime);
                    }
//                        $daoqitime = strtotime('+'.intval(I('tian')).' days',strtotime(date('H:i:s',time())));
                    //获取逾期的天数，根据押金扣除日志获取
//                        $yajinlogs = M('')->query('select count(1) num from tp_yajin_log tyl where tyl.type = 3 and tyl.oid = '.$fuorder['id']);
//                        if(!empty($yajinlogs)){
                    $tian = $tian + $yuqitian;
//                        }
                }
                $newData['status'] = 2;
                $newData['dao_qi_time'] = $daoqitime;
                $newData['price'] = $pay_money;
                $newData['pay_money'] = $pay_money;
                $newData['xuyajin'] = $xuyajin;
                $newData['tian'] = $tian;
                $result = M('ShopOrder')->where('id = '.$pid)->save($newData);
                //修改书的状态为借阅中
                M('Books')->where('id = '.$data['otherid'])->save(array('status'=>3));
                //修改扣除押金记录status为已补差价
                M('YajinLog')->where('oid = '.$pid.' and type = 3')->save(array('status'=>1));
            }

            $this->ajaxReturn(1);
        }
        //微信支付
        if(1 == $isweixin){

            if(I('price') <= 0){
                $eq['id'] = $log_id;
                M("ShopOrder")->where($eq)->setField('is_pay',1);
                return false;
            }
            $url = "https://".$_SERVER['HTTP_HOST']."/index.php/Tongcheng/Notify2?type=2";
//            echo $url;
//            $this->ajaxReturn($url);
            // echo $url;
            vendor('Weixinpay.WxPayJsApiPay');
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($data['title']);
            $input->SetAttach($data['title']);
            $input->SetOut_trade_no($data['out_trade_no']);
            $input->SetTotal_fee(($data['pay_money']*100));
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            // $input->SetGoods_tag("test3");
            $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($data['openid']);
            $input->SetAppid($appid);
            $input->SetMch_id($mch_id);
            try{
                $wxorder = \WxPayApi::unifiedOrder($input, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
            if($wxorder['return_code'] == "FAIL"){
                $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
                $this->ajaxReturn($arr);
            }
            try{
                $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
            }catch(Exception $e){
                $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
                $this->ajaxReturn($arr);
            }
            echo $jsApiParameters;
            exit();
        }

    }



    /**
     * 社团添加
     */
    public function sheTuan(){
        $formdata1 = json_decode($_POST['formData']);
        $formdata = $formdata1->shetuan->shetuan;
        if(empty($formdata)){
            $formdata = $formdata1->shetuan;
        }
        $uploadimages = $formdata1->uploadimages;
        foreach ($uploadimages as $key=>$item){
            $data['img'.($key+1)]=$item->filename;
        }
        //type 1书评，2话题，3问答，4写文
        $data['type'] = $formdata1->type;
        $data['title'] = $formdata->title;
        $data['content'] = $formdata->content;
        $data['xiangguanbook'] = $formdata->xiangguanbook;
        //处理文章类别
        $wenzhangtype = '';
        if(!empty($formdata1->temp)){
            foreach ($formdata1->temp as $key=>$item){
                if(!empty($item) && !empty($item->isselect)){
                    $wenzhangtype.=$item->btype.',';
                }
            }
        }
        $data['wenzhangtype'] = $wenzhangtype;
        $data['add_time'] = time();
        $data['wid'] = '2';
        $data['openid'] = '';
        $data['dianzan_num'] = 0;
        $data['liulan_num'] = 0;
        $data['uid'] = I('uid');
        if(!$log_id = M('Shetuan')->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(array('code'=>'0'),'json');
        }else{
            $this->ajaxReturn(array('code'=>'1'),'json');
        }
    }

    //获取社区首页数据
    public function getSheQuShouYeData(){
        $uid = I('uid');
        $keyword = I('keyword');
        $search = ' ';
        if(!empty($keyword)){
            $search = ' and s.title like "%'.$keyword.'%"';
        }
        //type 1书评，2话题，3问答，4写文
        $model = M('');
        $newResult = '';
        //获取热门书评
        $hot = $model->query('select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id where type = 1 '.$search.' order by id desc limit 2');
        $hot = $this->isDianZan($hot,$uid);
        $newResult['hot']=$hot;
        //获取推荐话题
        $tuijian = $model->query('select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id where type = 2 '.$search.' order by id desc limit 6');
        $tuijian = $this->isDianZan($tuijian,$uid);
        $tuijian1 = array();
        $tuijian2 = array();
        foreach ($tuijian as $key=>$item){
            if($key%2==0){
                array_push($tuijian1,$item);
            }else{
                array_push($tuijian2,$item);
            }
        }
        $newResult['tuijian1']=$tuijian1;
        $newResult['tuijian2']=$tuijian2;
        //获取精选问答
        $wenda = $model->query('select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id where type = 3 '.$search.' order by id desc limit 2');
        $wenda = $this->isDianZan($wenda,$uid);
        $newResult['wenda']=$wenda;
        //获取尝试写文
        $xiewen = $model->query('select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id where type = 4 '.$search.' order by id desc limit 2');
        $xiewen = $this->isDianZan($xiewen,$uid);
        $newResult['xiewen']=$xiewen;
        $this->ajaxReturn($newResult,'json');
    }

    /**
     * 获取搜索数据
     */
    public function getSheQuListBySearch(){
        $keyword = I('keyword');
        $type = I('type');
        $my = I('my');
        $uid = I('uid');
        $pagenum = I('pagenum');
        $pagesize = 5;
        $sql = '';
        if(!empty($keyword)){
            $sql .= ' and (s.title like "%'.$keyword.'%" or s.content like "%'.$keyword.'%")';
        }
        if(!empty($uid) && !empty($my)){
            $sql .= ' and s.uid = '.$uid;
        }
        $order = ' order by s.id desc limit '.(intval($pagenum)-1)*$pagesize.','.$pagesize;
        $shetuanlist = M('')->query(' select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id  where s.type = '.$type.$sql.$order);
        $shetuanlist = $this->isDianZan($shetuanlist,$uid);
        if(empty($shetuanlist)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($shetuanlist,'json');
        }
    }

    //获取社区分页数据
    public function getSheQuList(){
        //type 1书评，2话题，3问答，4写文
        $model = M('');
        $type = I('type');
        $uid = I('uid');
        $pagenum = I('pagenum');
        $pagesize = 3;
        if(empty($type)){
            $this->ajaxReturn(0);
        }
        $list = $model->query('select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id where s.type = '.$type.' order by id desc limit '.($pagenum-1)*$pagesize.','.$pagesize);
        if(empty($list)){
            $this->ajaxReturn(0);
        }else{
            $list = $this->isDianZan($list,$uid);
            $this->ajaxReturn($list,'json');
        }
    }

    //获取社团详情

    public function getSheQuanInfo(){
        $model = M('');
        $id = I('id');
        $uid = I('uid');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $shequan = $model->query('select * from tp_shetuan s left join tp_member m on m.uid = s.uid left join pinglun_num pn on pn.otherid = s.id  where  s.id = '.$id);

        if(empty($shequan[0])){
            $this->ajaxReturn(0);
        }else{
            $pinglunlist = $model->query('select *,FROM_UNIXTIME(pl.add_time,"%m-%d %H:%i") time from tp_pinglun pl left join tp_member m on m.uid = pl.uid where pl.otherid = '.$id.' and pl.from = '.(intval($shequan[0]['type'])+2));
            if(!empty($pinglunlist)){
                //获取回复数据
                foreach ($pinglunlist as &$item){
                    if(!empty($item)){
                        $huifus = $model->query('select *,m.nickname from tp_pinglun tl left join tp_member m on m.uid = tl.uid where tl.from = 7 and tl.otherid = '.$item['id']);
                        $item['huifuscount'] = count($huifus);
                        if(count($huifus) > 3){
                            $huifusnew = array();
                            array_push($huifusnew,$huifus[0]);
                            array_push($huifusnew,$huifus[1]);
                            array_push($huifusnew,$huifus[2]);
                        }else{
                            $huifusnew = $huifus;
                        }
                        $item['huifus'] = $huifusnew;
                    }
                }
                unset($item);
            }
            $shequan[0]['pinglunlist'] = $pinglunlist;
            $shequan[0]['pingluncount'] = count($pinglunlist);
            $shequan = $this->isDianZan($shequan,$uid);
            $this->ajaxReturn($shequan[0],'json');
        }
    }

    /**
     * @param $code
     * @return null|string
     * 上传图片
     */
    protected function upload($code){
        date_default_timezone_set("Asia/Shanghai"); //设置时区
        if(is_uploaded_file($_FILES['file']['tmp_name'])) {
            //把文件转存到你希望的目录（不要使用copy函数）
            $uploaded_file=$_FILES['file']['tmp_name'];
            $username = "min_img";
            //我们给每个用户动态的创建一个文件夹
            $user_path=$_SERVER['DOCUMENT_ROOT']."/m_pro/".$username;
            //判断该用户文件夹是否已经有这个文件夹
            if(!file_exists($user_path)) {
                mkdir($user_path);
            }
            //$move_to_file=$user_path."/".$_FILES['file']['name'];
            $file_true_name=$_FILES['file']['name'];
            $newfilename = time().rand(1,1000)."-".date("Y-m-d").substr($file_true_name,strrpos($file_true_name,"."));
            $move_to_file=$user_path."/".$newfilename;//strrops($file_true,".")查找“.”在字符串中最后一次出现的位置
            //echo "$uploaded_file   $move_to_file";
            if(move_uploaded_file($uploaded_file,$move_to_file)) {
                return 'http://'.$_SERVER['HTTP_HOST'].'/m_pro/min_img/'.$newfilename;
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    //判断是否点赞，并返回新的数据
    public function isDianZan($list,$uid){
        if(empty($uid) || 'undefined' == $uid){
            return $list;
        }
        $model = M('');
        $newList = array();
        foreach ($list as &$item){
            if(!empty($item)){
                $dianzancount = 0;
                $dianzanlog = $model->query('select * from tp_dianzan_log dl where dl.uid = '.$uid.' and dl.otherid = '.$item['id'].' and dl.from = '.(intval($item['type'])+2));
                if(!empty($dianzanlog)){
                    $item['isDianZan'] = 1;
                }else{
                    $item['isDianZan'] = 0;
                }

                //获取点赞数目
                $countList = $model->query('select * from tp_dianzan_log dl where dl.otherid = '.$item['id'].' and dl.from = '.(intval($item['type'])+2));
                if(!empty($countList)){
                    $dianzancount = count($countList);
                }
                $item['dianzan_num'] = $dianzancount;
                array_push($newList,$item);
            }
        }
        unset($item);
        return $newList;
    }


    //获取订单列表
    public function getOrderListByUid(){
        $type = I('type');
        $type = $type==0?2:1;
        $uid = I('uid');
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        $status = I('status');
        $pagesize = 5;
        $pagenum = I('pagenum');
        $model = M('');
        //type 1图书订单  2闲置订单
        $join = ' ';
        if(1 == $type){
            $join.=' left join tp_books tb on tb.id = tso.otherid ';
        }else if(2 == $type){
            $join.=' left join tp_unuse tb on tb.id = tso.otherid ';
        }
        $where = ' ';
        if(!empty($status)){
            $where.=' and tso.status = '.$status;
        }
        $order = ' order by tso.id desc limit '.($pagenum-1)*$pagesize.','.$pagesize;
        $sql = 'select tso.id oid,tso.status ostatus,tso.create_time ocreate_time,tso.*,m.*,tb.* from tp_shop_order tso left join tp_member m on m.uid = tso.uid '.$join.' where tso.isdel=0 and tso.type = '.$type.' and tso.uid = '.$uid.$where.$order;
        $orderlist = $model->query('select tso.id oid,tso.status ostatus,tso.create_time ocreate_time,tso.*,m.*,tb.*,(round(ifnull(tso.pay_money,0),2)-round(ifnull(tso.xuyajin,0),2)) cha from tp_shop_order tso left join tp_member m on m.uid = tso.uid '.$join.' where tso.isdel=0 and  tso.type = '.$type.' and tso.uid = '.$uid.$where.$order);
        //如果是图书并且在借阅中，判断是否逾期
        $time = time();
        if(1 == $type){
            foreach ($orderlist as &$item){
                if(2 <= intval($item['ostatus']) && intval($item['ostatus']) <= 3){
                    $member = M('Member')->where('uid = '.$uid)->find();
                    $book = M('Books')->where('id = '.$item['otherid'])->find();
                    //如果当前时间大于到期时间说明已到期
                    if($time > intval($item['dao_qi_time'])){
                        //修改订单状态为已逾期
                        M('ShopOrder')->where('id = '.$item['oid'])->save(array('status'=>3));
                        //更新书本状态为已逾期
                        M('Books')->where('id = '.$item['otherid'])->save(array('status'=>4));
                        //增加逾期系统通知
                        $this->addXiTongLog($item['oid'],4,$uid,$book['uid'],$item['otherid'],'');

                    }

                    //增加扣除押金的记录
                    //1查询是否有记录有未补差价的记录
                    $log = M('YajinLog')->where('oid = '.$item['oid'].' and type=3 and status = 0')->select();
                    $logcount = count($log);
                    //2 计算超出的时间差
                    $cha = $time-intval($item['dao_qi_time']);

                    //修改扣除记录为逾期后第二天开始计算  原是!empty($item['dao_qi_time']) && $cha/86400>=1 && ($logcount+1)<=$cha/86400
                    if(!empty($item['dao_qi_time']) && $cha/86400>=1 && ($logcount+1)<=$cha/86400){
                        //3记录押金扣除记录
                        $j = $cha/86400;
                        for($i=1;$i<$j;$i++){
                            //增加押金记录
                            $this->yaJinLog($item['oid'],3,$book['rent'],$uid);
                            //4并扣除冻结押金
                            M('Member')->where('uid = '.$uid)->save(array('dong_jie_yajin'=>(floatval($member['dong_jie_yajin'])-floatval($book['rent']))));
                        }
                    }
                }
            }
        }
        $orderlist = $model->query('select tso.id oid,tso.status ostatus,tso.create_time ocreate_time,tso.*,m.*,tb.*,(round(ifnull(tso.pay_money,0),2)-round(ifnull(tso.xuyajin,0),2)) cha from tp_shop_order tso left join tp_member m on m.uid = tso.uid '.$join.' where tso.isdel=0 and tso.type = '.$type.' and tso.uid = '.$uid.$where.$order);
        //获取续借的子菜单
        foreach ($orderlist as &$item){
            if(empty($item)){
                continue;
            }
            $xulist = $model->query('select COUNT(1) num,ifnull(sum(tian),0) tiannum from tp_shop_order tp where pid = '.$item['oid'].' GROUP BY pid ');
            $item['xulistcount'] = $xulist[0]['num'];
            $item['tiannum'] = $xulist[0]['tiannum'];
            $item['zongtian'] = intval($item['tian']);// + intval($item['tiannum']);
        }
        unset($item);
        if(empty($orderlist)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($orderlist,'json');
        }
    }

    /**
     * @param $oid
     * @param $type
     * @param $amount
     * @param $uid
     * 增加押金记录
     */
    public function yaJinLog($oid,$type,$amount,$uid){
        $data['oid'] = $oid;
        $data['type'] = $type;//1冻结押金2活动押金3扣除押金
        $data['status'] = 0;//0未补差价 1补差价
        $data['add_time'] = time();
        $data['amount'] = $amount;
        $data['uid'] = $uid;
        M('YajinLog')->add($data);
    }


    //获取订单列表
    public function xujiedingdan(){
        $pid = I('pid');
        if(empty($pid)){
            $this->ajaxReturn(0);
        }
        $pagesize = 5;
        $pagenum = I('pagenum');
        $model = M('');
        $join = ' ';
        $join.=' left join tp_books tb on tb.id = tso.otherid ';
        $where = ' ';
        if(!empty($status)){
            $where.=' and tso.status = '.$status;
        }
        $order = ' order by tso.id desc limit '.($pagenum-1)*$pagesize.','.$pagesize;
//        $sql = 'select tso.id oid,tso.status ostatus,tso.*,m.*,tb.* from tp_shop_order tso left join tp_member m on m.uid = tso.uid '.$join.' where tso.type = '.$type.' and tso.uid = '.$uid.$where.$order;
        $orderlist = $model->query('select tso.id oid,tso.status ostatus,tso.*,m.*,tb.* from tp_shop_order tso left join tp_member m on m.uid = tso.uid '.$join.' where tso.type = 4 and tso.pid = '.$pid.$where.$order);
        //如果是图书并且在借阅中，判断是否逾期
        if(empty($orderlist)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($orderlist,'json');
        }
    }


    /**
     * 获取扣除的押金
     */
    public function getKouChuYaJin(){
        $uid = I('uid');
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        $result = M('')->query('select sum(amount) num from tp_yajin_log where type = 3 and uid = '.$uid);
        if(!empty($result)){
            $this->ajaxReturn($result[0]['num']);
        }else{
            $this->ajaxReturn(0);
        }

    }

    /**
     * 删除订单
     */
    public function delOrderById(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $model = M('ShopOrder');
        $data['id'] = $id;
        $del = $model->where("id=".$id)->save(array('isdel'=>1));
        if(!empty($del)){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 确认订单已完成
     */
    public function wanChengOrderById(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $model = M('ShopOrder');
        $result = $model->where('id = '.$id)->save(array('status'=>4));
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 归还图书
     */
    public function guiHuanBook(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $model = M('ShopOrder');
        $shopOrder = $model->where('id = '.$id)->find();
        if(empty($shopOrder)){
            $this->ajaxReturn(0);
        }
        $member = M('Member')->where('uid = '.$shopOrder['uid'])->find();
        if(empty($member)){
            $this->ajaxReturn(0);
        }
        //归还更新冻结押金和活动押金
        //获取扣费的金额
        $koufei = 0;
        $yajinlist = M('')->query('select ifnull(sum(amount),0) num from tp_yajin_log where type = 3 and oid = '.$id);
        if(!empty($yajinlist[0])){
            $koufei = $yajinlist[0]['num'];
        }
        $yajin = floatval($member['yajin']) + (floatval($shopOrder['yuanjia']) - floatval($koufei));
        $dong_jie_yajin = floatval($member['dong_jie_yajin']) - (floatval($shopOrder['yuanjia']) - floatval($koufei));
        //增加活动押金记录
        $this->yaJinLog($id,2,(floatval($shopOrder['yuanjia']) - floatval($koufei)),$shopOrder['uid']);
        //更新订单状态
        $result = $model->where('id = '.$id)->save(array('status'=>4));
        //更新图书状态
        M('Books')->where('id = '.$shopOrder['otherid'])->save(array('status'=>5));
        $book = M('Books')->where('id = '.$shopOrder['otherid'])->find();
        //更新用户押金状态
        if($result){
            $result = M('Member')->where('uid = '.$shopOrder['uid'])->save(array('yajin'=>$yajin,'dong_jie_yajin'=>$dong_jie_yajin));
            if($result){
                //增加系统通知
                $this->addXiTongLog($id,3,$shopOrder['uid'],$book['uid'],$shopOrder['otherid'],'归还增加可退押金'.(floatval($shopOrder['yuanjia']) - floatval($koufei)));
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 确认收到书或者收到闲置
     */
    public function quRenShouHuo(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $model = M('ShopOrder');
        $shoporder = $model->where('id = '.$id)->find();
        if(empty($shoporder)){
            $this->ajaxReturn(0);
        }
        //图书
        if(1 == $shoporder['type']){
            //根据借的天数，计算到期时间戳
            $dao_qi_time = strtotime('+'.$shoporder['tian'].' day');
            $result = $model->where('id = '.$id)->save(array('status'=>2,'dao_qi_time'=>$dao_qi_time));
            //修改图书状态为借阅中
            M('Books')->where('id = '.$shoporder['otherid'])->save(array('status'=>3));
        }else{//闲置
            $result = $model->where('id = '.$id)->save(array('status'=>4,'shuzhu_quren'=>1));

            //更新闲置状态初始化
            M('Unuse')->where('id = '.$shoporder['otherid'])->save(array('order_id'=>0,'status'=>0));
            $unuse = M('Unuse')->where('id = '.$shoporder['otherid'])->find();
            //计算收入到余额中
            $this->changeYueByOrderId($id);

        }

        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 删除书
     */
    public function delBook(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $result = M('Books')->where('id = '.$id)->delete();
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 删除闲置
     */
    public function delUnuse(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $result = M('Unuse')->where('id = '.$id)->delete();
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 删除社区
     */
    public function delSheQu(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $result = M('Shetuan')->where('id = '.$id)->delete();
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 更新用户信息
     */
    public function updateUserInfo(){
        $formdata = json_decode($_POST['formData']);
        $model = M('Member');
        $result = $model->where('uid = '.$formdata->uid)->save($formdata->formdata);
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 获取用户共享信息
     */
    public function getGongXiangListByUid(){
        $formData = json_decode($_POST['formData']);
        $from = I('type');
        $uid = I('uid');
        $pagesize = 5;
        $pagenum = I('pagenum');
        if(empty($uid) || 'undefined'==$uid){
            $this->ajaxReturn(0);
        }
        $model = M('');
        $table = 'tp_unuse';
        if(!empty($from) && 1 == $from){
            $table = 'tp_books';
        }
        $order = ' order by order_id desc,id desc limit '.($pagenum-1)*$pagesize.','.$pagesize;
        $sql = 'select * from '.$table.' where 1=1 and uid = '.$uid.$order;
        $datalist = $model->query($sql);
        if(empty($datalist)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($datalist,'json');
        }
    }

    /*
     * 下架图书
     */
    public function xiajiabook(){
        $id = I('id');
        $status = I('upstatus')==0?1:0;
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $data['id'] = $id;
        $data['upstatus'] = $status;
        $data['add_time'] = time();

        $result = M('Books')->where("id = ".$id)->save($data);
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 下架闲置
     */
    public function xiajiaunuse(){
        $id = I('id');
        $status = I('status')==0?1:0;
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $data['id'] = $id;
        $data['status'] = $status;
        $data['add_time'] = time();

        $result = M('Unuse')->where("id = ".$id)->save($data);
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 更新浏览数
     */
    public function liuLanNum(){
        $id = I('id');
        $from = I('from');
        if(empty($id) || empty($from)){
            $this->ajaxReturn(0);
        }
        $model = M('');
        //1闲置  2图书 3社区
        if(1 == intval($from)){
            $unuse = $model->query('select * from tp_unuse where id = '.$id);
            if(!empty($unuse[0])){
                $result = M('Unuse')->where('id = '.$id)->save(array('liulan_num'=>intval($unuse[0]['liulan_num']) + 1));
                if($result){
                    $this->ajaxReturn(intval($unuse[0]['liulan_num']) + 1);
                }else{
                    $this->ajaxReturn(0);
                }
            }
        }else if(2 == intval($from)){
            $book = $model->query('select * from tp_books where id = '.$id);
            if(!empty($unuse[0])){
                $result = M('Books')->where('id = '.$id)->save(array('liulan_num'=>intval($unuse[0]['liulan_num']) + 1));
                if($result){
                    $this->ajaxReturn(intval($unuse[0]['liulan_num']) + 1);
                }else{
                    $this->ajaxReturn(0);
                }
            }
        }else if(3 == intval($from)){
            $shequ = $model->query('select * from tp_shetuan where id = '.$id);
            if(!empty($shequ[0])){
                $result = M('Shetuan')->where('id = '.$id)->save(array('liulan_num'=>intval($shequ[0]['liulan_num']) + 1));
                if($result){
                    $this->ajaxReturn(intval($shequ[0]['liulan_num']) + 1);
                }else{
                    $this->ajaxReturn(0);
                }
            }
        }
    }

    /**
     * @throws \WxPayException
     * 余额充值
     */
    public function chongzhi(){
        $uid = I('uid');
        $amount = I('price');
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        if(empty($amount)){
            $this->ajaxReturn(0);
        }
        $map['wid'] = 2;
        $wechat = M("Wechat")->where($map)->find();

//        $top = M("Join")->where(array('id'=>$_POST['join_id']))->find();
//        $join_fee = $top['price'];
//        $join_days = $top['days'];

//        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = 2;//session('wid');
//        $data['shop_id'] = I('shop_id');
        $data['uid'] = $uid;
//        $data['otherid'] = I('otherid');
        $data['openid'] = I('openid');
        $data['out_trade_no'] = 'CZ'.$this->build_order_no();
//        $data['transaction_id'] = 'CZ'.$this->build_order_no();
        $data['title'] = "充值余额";
//        $data['remark'] = $_POST['name'];
        $data['price'] = $amount;
        $data['pay_money'] = $amount;
        $data['shouru'] = $amount;
//        $data['join_days'] = $join_days;
        $data['status'] = 1;//待支付
        $data['is_pay'] = 0;
        $data['type'] = 3;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$log_id = M("ShopOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }
        if($amount <= 0){
            $eq['id'] = $log_id;
            M("ShopOrder")->where($eq)->setField('is_pay',1);
            return false;
        }
        $url = "https://".$_SERVER['HTTP_HOST']."/index.php/Tongcheng/Notify2?type=3";
//        echo $url;
//        $this->ajaxReturn($url);
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['title']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($data['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);
        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;
        exit();
    }

    /**
     * @throws \WxPayException
     * 余额充值
     */
    public function chongzhiyajin(){
        $uid = I('uid');
        $amount = I('price');
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        if(empty($amount)){
            $this->ajaxReturn(0);
        }
        $map['wid'] = 2;
        $wechat = M("Wechat")->where($map)->find();

//        $top = M("Join")->where(array('id'=>$_POST['join_id']))->find();
//        $join_fee = $top['price'];
//        $join_days = $top['days'];

//        $all_money = $join_fee;
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $data['wid'] = 2;//session('wid');
//        $data['shop_id'] = I('shop_id');
        $data['uid'] = $uid;
//        $data['otherid'] = I('otherid');
        $data['openid'] = I('openid');
        $data['out_trade_no'] = 'YJ'.$this->build_order_no();
//        $data['transaction_id'] = 'CZ'.$this->build_order_no();
        $data['title'] = "充值押金";
//        $data['remark'] = $_POST['name'];
        $data['price'] = $amount;
        $data['pay_money'] = $amount;
//        $data['join_days'] = $join_days;
        $data['status'] = 1;//待支付
        $data['is_pay'] = 0;
        $data['type'] = 4;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!$log_id = M("ShopOrder")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn(0);
        }
        if($amount <= 0){
            $eq['id'] = $log_id;
            M("ShopOrder")->where($eq)->setField('is_pay',1);
            return false;
        }
        $url = "https://".$_SERVER['HTTP_HOST']."/index.php/Tongcheng/Notify2?type=3";
//        echo $url;
//        $this->ajaxReturn($url);
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['title']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($data['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);
        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        echo $jsApiParameters;
        exit();
    }

    /**
     * 获取收入明细包括自己的支出明细
     */
    public function shouRuMingxi(){
        $uid = I('uid');
        $type = I('type');//1总收入明细2充值里面的明细
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        $where = ' ';
        if(1 == $type){
            $where.=' and so.shuzhu_quren = 1 ';
        }
        //根据otheruid 订单获取个人的收入明细
        $shoporder = M('')->query('select *,round(so.pay_money,2) pay_money1,round(ifnull(so.xuyajin,0),2) xuyajin1,(round(so.shouru,2)) cha1 ,1 shouru1,"收入" biaozhu from tp_shop_order so where 1=1 and so.type != 4 '.$where.'  and  so.otheruid = '.$uid.' order by so.last_time desc');
        //根据uid 订单获取个人的支出明细
        $zhichuorder = array();
        if(2 == $type){
            $shoporder = M('')->query('select * from (select *,round(so.pay_money,2) pay_money1,round(ifnull(so.xuyajin,0),2) xuyajin1,(round(so.shouru,2)) cha1 ,1 shouru1,"收入" biaozhu from tp_shop_order so where 1=1 and so.type != 4  '.$where.'  and  so.otheruid = '.$uid.'  union all select *,round(so.pay_money,2) pay_money1,round(ifnull(so.xuyajin,0),2) xuyajin1,(round(so.shouru,2)) cha1 ,0 shouru1,"支出" biaozhu  from tp_shop_order so where  so.type != 4 '.$where.' and so.uid != so.otheruid and so.uid = '.$uid.') as t1 order by t1.last_time desc ');
        }

//        if(empty($shoporder)){
//            $this->ajaxReturn(0);
//        }
        $this->ajaxReturn(array_merge($shoporder,$zhichuorder),'json');
    }

    /**
     * 押金明细
     */
    public function yaJinMingXi(){
        $uid = I('uid');
        //购书产生的押金
//
//        $maiyajinlist = M('')->query('select *,t.xuyajin cha1,1 shouru,"购书押金" biaozhu from tp_shop_order t where t.type = 1 and t.xuyajin > 0 and t.uid = '.$uid);
//
//        //逾期扣除的押金明细
//        $kouyajinlist = M('')->query('select *,t.amount pay_money,0 shouru,"逾期扣除" biaozhu from tp_yajin_log t left join tp_shop_order s on s.id = t.oid where t.uid = '.$uid);

        $loglist = M('')->query('select *,FROM_UNIXTIME(t.add_time,"%Y-%m-%d %H:%i:%s") create_time,(case when t.type = 1 then "冻结押金" when t.type = 2 then "解封押金" else "扣除押金" end) as biaozhu from tp_yajin_log t left join tp_shop_order s on s.id = t.oid where t.uid = '.$uid.' order by t.id desc');

        $this->ajaxReturn($loglist,'json');
    }

    /**
     * 获取订单详情
     */
    public function getShopOrderInfo(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $shoporder = M('ShopOrder')->where('id = '.$id)->select();
        if(empty($shoporder[0])){
            $this->ajaxReturn(0);
        }
        //1 图书 2闲置
        if(1 == intval($shoporder[0]['type'])){
            $goodinfo = M('')->query('select * from tp_books t where t.id = '.$shoporder[0]['otherid']);
        }else if(2 == intval($shoporder[0]['type'])){
            $goodinfo = M('')->query('select * from tp_unuse t where t.id = '.$shoporder[0]['otherid']);
        }
        if(!empty($goodinfo[0])){
            $shoporder[0]['goodinfo'] = $goodinfo[0];
        }else{
            $shoporder[0]['goodinfo'] = array();
        }
        $this->ajaxReturn($shoporder[0],'json');
    }

    /**
     * 获取轮播图
     */
    public function getLunboList(){
        $type = I('type');
        $lunbolist = M('')->query('select * from tp_lunbo t where t.status = 1 and t.type = '.$type.' order by t.order asc ');
        if(empty($lunbolist)){
            $this->ajaxReturn(array(),'json');
        }else{
            $this->ajaxReturn($lunbolist,'json');
        }
    }

    /**
     * 取消收藏
     */
    public function quXiaoShouCang(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $result = M('ShoucangLog')->where('id = '.$id)->delete();

        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 确认归还
     */
    public function queRenGuiHuan(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $books = M('Books')->where('id = '.$id)->find();
        if(empty($books)){
           $this->ajaxReturn(0);
        }
        //根据图书的order_id获取订单信息
        $shoporder = M('ShopOrder')->where('id = '.$books['order_id'])->find();
        if(empty($shoporder)){
           $this->ajaxReturn(0);
        }
        if(4 != $shoporder['status']){
            $this->ajaxReturn(2);
        }
        //修改shuzhu_quren为1，表示书主确认收货，总收入显示
        M('ShopOrder')->where('id = '.$books['order_id'])->save(array('shuzhu_quren'=>1));
        $this->changeYueByOrderId($books['order_id']);
        //确认归还后，状态修改为初始
        $result = M('Books')->where('id = '.$id)->save(array('status'=>1,'upstatus'=>1,'order_id'=>0));
        if($result){
            //增加系统收入通知
            $this->addXiTongLog($books['order_id'],5,$shoporder['uid'],$books['uid'],$books['id']);
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 获取用户系统通知列表
     */
    public function getXitonLogList(){
        $type = I('type');
        $uid = I('uid');
        $pagenum = I('pagenum');
        $pagesize = 10;
        $order = ' order by id desc limit '.(intval($pagenum)-1)*$pagesize.','.$pagesize;
        //获取我卖的东西的系统通知
        $xitonglist = M('')->query('select *,m.nickname,0 buy,0 mlog from tp_xitong_log xl left join tp_member m on m.uid = xl.uid where xl.maiuid = '.$uid.$order);
        if(empty($xitonglist)){
            $this->ajaxReturn(array());
        }
        //获取我买的东西的系统通知
//        $myXiTongList = M('')->query('select *,m.nickname,1 buy from tp_xitong_log xl left join tp_member m on m.uid = xl.uid where xl.uid = '.$uid.$order);
//        $xitonglist = array_merge($xitonglist,$myXiTongList);
        foreach ($xitonglist as &$item){
            if(1 == intval($item['type']) || 6 == intval($item['type'])){
                $goods = M('Unuse')->where('id = '.$item['goods_id'])->find();
                if(!empty($goods)){
                    $item['goodname'] = $goods['unuse_name'];
                    $item['goodoid'] = $goods['order_id'];
                }else{
                    $item['goodname'] = '';
                    $item['goodoid'] = 0;
                }

            }else if(2 == intval($item['type']) || 3 == intval($item['type']) || 4 == intval($item['type']) || 5 == intval($item['type']) || 7 == intval($item['type'])){
                $goods = M('Books')->where('id = '.$item['goods_id'])->find();
                if(!empty($goods)){
                    $item['goodname'] = $goods['book_name'];
                    $item['goodoid'] = $goods['order_id'];
                }else{
                    $item['goodname'] = '';
                    $item['goodoid'] = 0;
                }
            }
            //1闲置2图书3借书归还4借书逾期5收入6闲置确认收获
            switch (intval($item['type'])){
                case 1:
                    $item['xiTongLogType']='闲置';
                    break;
                case 2:
                    $item['xiTongLogType']='图书';
                    break;
                case 3:
                    $item['xiTongLogType']='借书归还';
                    break;
                case 4:
                    $item['xiTongLogType']='借书逾期';
                    break;
                case 5:
                    $item['xiTongLogType']='借书收入';
                    break;
                case 6:
                    $item['xiTongLogType']='闲置收货';
                    break;
                case 7:
                    $item['xiTongLogType']='借书续借';
                    break;
            }
        }
        unset($item);
        $xiTongFaBu = M('')->query('select t.id,t.title,FROM_UNIXTIME(t.add_time,"%Y-%m-%d %H:%i:%s") time,1 mlog from tp_back_xitong t where t.status=1 order by id desc ');
        $newlist = array_merge($xiTongFaBu,$xitonglist);

        $this->ajaxReturn($newlist,'json');
    }

    /**
     * 获取用户通知数目
     */
    public function getXitongLogCount(){
        $type = I('type');
        $uid = I('uid');
        $xitonglist = M('XitongLog')->where(array('maiuid'=>$uid,'status'=>0))->select();
        if(empty($xitonglist)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn(count($xitonglist));
        }
    }

    /**
     * 卖家确认发货
     */
    public function queRenFaHuo(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $shoporder = M('ShopOrder')->where('id = '.$id)->find();
        if(empty($shoporder)){
            $this->ajaxReturn(0);
        }
        if($shoporder['status']>2){
            $this->ajaxReturn(2);
        }
        $kuaidi_sn = I('kuaidi_sn');
        $kuaidi_com = I('kuaidi_com');
        $fahuo_time = date('Y-m-d H:i:s',time());
        $result = M('ShopOrder')->where('id = '.$id)->save(array('kuaidi_sn'=>$kuaidi_sn,'kuaidi_com'=>$kuaidi_com,'status'=>3,'fahuo_time'=>$fahuo_time));
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    //根据订单处理用户的余额信息
    public function changeYueByOrderId($orderid){
        $map['wid'] = 2;
        $wechat = M("Wechat")->where($map)->find();
        $shoporder = M('ShopOrder')->where('id = '.$orderid)->find();
        if(empty($shoporder)){
            return 0;
        }
        $shouRu = floatval($shoporder['pay_money'])-floatval($shoporder['xuyajin']==null?0:$shoporder['xuyajin']);//
        //卖家增加收入
        $maijia = M('Member')->where('uid = '.$shoporder['otheruid'])->find();
        if(empty($maijia)){
            return 0;
        }
        //图书抽成
        $pingTaiFei = $shouRu * (intval($wechat['withdraw_rate'])/100);
        if(2 == intval($shoporder['type'])){
            //闲置抽成
            $pingTaiFei = $shouRu * (intval($wechat['withdraw_rate1'])/100);
            //增加闲置确认收货通知
            $this->addXiTongLog($orderid,6,$shoporder['uid'],$maijia['uid'],$shoporder['otherid'],'余额增加'.($shouRu - $pingTaiFei).'平台费为：'.$pingTaiFei);
        }
        $yue = floatval($maijia['yu_e_num']) + $shouRu - $pingTaiFei;
        $result = M("Member")->where('uid = '.$shoporder['otheruid'])->save(array('yu_e_num'=>$yue));
        //更新订单的平台费金额及完成时间last_time
        M('ShopOrder')->where('id = '.$orderid)->save(array('shouru'=>($shouRu - $pingTaiFei),'pingtaifei'=>$pingTaiFei,'last_time'=>date("Y-m-d H:i:s")));
        if($result){
            //记录平台费用
            $data['order_id']=$orderid;
            $data['type']=$shoporder['type'];
            $data['add_time']=time();
            $data['amount']=$pingTaiFei;
            $data['remark']='平台抽成';
            M('PingtaiChoucheng')->add($data);
            return 1;
        }else{
            return 0;
        }

    }

    /**
     * 获取回复列表
     */
    public function getHuiFuList(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $pinglun = M('')->query('select *,FROM_UNIXTIME(t.add_time,"%m-%d %H:%i") time from tp_pinglun t left join tp_member m on m.uid = t.uid where id = '.$id);
        if(empty($pinglun[0])){
            $this->ajaxReturn(0);
        }
        $huifulist = M('')->query('select *,FROM_UNIXTIME(t.add_time,"%m-%d %H:%i") time from tp_pinglun t left join tp_member m on m.uid = t.uid where t.otherid = '.$id.' and t.from = 7');
        if(empty($huifulist)){
            $pinglun[0]['huifulist']=array();
        }else{
            $pinglun[0]['huifulist']=$huifulist;
        }
        $this->ajaxReturn($pinglun[0],'json');
    }

    /**
     * 获取今日收入
     */
    public function getShouYiByDay(){
        $uid = I('uid');
        if(empty($uid)){
            $this->ajaxReturn(0);
        }
        $where = ' and DATE_FORMAT(STR_TO_DATE(so.last_time,"%Y-%m-%d %H:%i:%s"),"%Y-%m-%d")="'.date('Y-m-d').'"';

        $sql = 'select ifnull(sum(round(so.shouru,2)),0) cha1 from tp_shop_order so where so.shuzhu_quren = 1 and  so.otheruid = '.$uid.$where.' ';
//        $this->ajaxReturn($sql);
        $shoporder = M('')->query($sql);
        if(empty($shoporder[0])){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($shoporder[0]);
        }
    }

    /**
     * 删除系统信息
     */
    public function delXiTongLog(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        $result = M('XitongLog')->where('id = '.$id)->delete();
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }
    /**
     * @param $list
     * 去除null操作
     */
    private function quNull($list){
        if(is_array($list)){
            foreach ($list as &$item){

            }
        }else{

        }
    }

    /**
     * 关于我们
     */
    public function getAboutUs(){
        $type = I('type');
        $aboutus = M('Aboutus')->where('type = '.$type)->find();
        header("Content-Type: text/html; charset=utf-8");
        $str='<style>body{font-size:40px;margin:10px;}img{width:100%;height:auto;}</style>'.$aboutus['content'];
        echo $str;
    }
    /**
     * 获取发现广告
     */
    public function getFindGuangGao(){
        $id = I('id');
        $guanggao = M('Guanggao')->where('id = '.$id)->find();
        header("Content-Type: text/html; charset=utf-8");
        $str='<style>body{font-size:40px;margin:10px;}img{width:100%;height:auto;}</style>'.$guanggao['content'];
        echo $str;
    }

    /**
     * 获取推荐
     */
    public function getTuiJian(){
        $tuijian = M('Tuijian')->limit(1)->find();
        if(empty($tuijian)){
            $this->ajaxReturn(0);
        }else{
            $this->ajaxReturn($tuijian,'json');
        }
    }

    /**
     * 意见反馈
     */
    public function yiJianFanKui(){
        $_POST['add_time'] = time();
        $result = M('KefuWenda')->add($_POST);
        if($result){
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(0);
        }
    }

    /**
     * 获取文章分类
     */
    public function getWenZhangType(){
        $bookslist = $this->getDocDicByType('wenzhangtype');
        if(empty($bookslist)){
            $this->ajaxReturn(0);
        }
        $this->ajaxReturn($bookslist);
    }

    /**
     * 设置为已读
     */
    public function readXiTong(){
        $id = I('id');
        if(empty($id)){
            $this->ajaxReturn(0);
        }
        M('XitongLog')->where('id = '.$id)->save(array('status'=>1));
    }

    /**
     * 获取系统通知
     */
    public function getXiTong(){
        $id = I('id');
        $aboutus = M('BackXitong')->where('id = '.$id)->find();
        header("Content-Type: text/html; charset=utf-8");
        $str='<style>body{font-size:40px;margin:10px;}img{width:100%;height:auto;}</style>'.$aboutus['content'];
        echo $str;
    }

    protected function build_order_no(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}